package eu.telecombretagne.rsm.gui.frames.panels;

import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTextField;

import eu.telecombretagne.rsm.gui.frames.DesktopFrame;

public abstract class SettingsPanel extends JPanel {
	
	private static final long serialVersionUID = -8650143999723912988L;
	
	/**
	 * Reads all the parameters.
	 */
	public void readAllParams(){
		readProbabilities();
		readDelays();
		readEffects();
	}
	
	protected abstract void readProbabilities();
	protected abstract void readDelays();
	protected abstract void readEffects();
	
	protected abstract Long setEventDelay(JTextField pTextField);
	protected abstract Double setEventProbability(JTextField pTextField);
	protected abstract void setEventEffects(EffectsPanel pEffectsPanel);
	
	protected Double getTextFromFieldAndParseToDouble(JTextField pTextField){
		Double value = null;
		
		try {
			value = Double.parseDouble(pTextField.getText());
		} catch(NumberFormatException nfe){
			DesktopFrame.writeLogError("Error! The argument " + pTextField.getText() + " is not a number. Setting a default value.");
		}
		
		return value;
	}
	
	protected Long getTextFromFieldAndParseToLong(JTextField pTextField){
		Long value = null;
		
		try {
			value = Long.parseLong(pTextField.getText());
		} catch(NumberFormatException nfe){
			DesktopFrame.writeLogError("Error! The argument " + pTextField.getText() + " is not a number. Setting a default value.");
		}
		
		return value;
	}
	
	protected JPanel createSubPanel(JComponent pFirstComponent, JComponent pSecondComponent){
		JPanel panel = new JPanel();
		panel.setLayout(new GridLayout(1, 2));
		
		pFirstComponent.setBorder(BorderFactory.createLineBorder(new Color(0,128,0)));
		pSecondComponent.setBorder(BorderFactory.createLineBorder(new Color(128,0,0)));
		
		panel.add(pFirstComponent);
		panel.add(pSecondComponent);
		
		return panel;
	}
	
	/**
	 * Sets panel locked.
	 * @param pLocked If set to <i>true</i> the panel is going to be locked.
	 */
	public void setPanelLocked(Boolean pLocked){
		Component[] components = this.getComponents();
		setLockedComponents(components, pLocked);
	}
	
	private void setLockedComponents(Component[] pComponents, Boolean pLocked){
		for(int i = 0; i < pComponents.length; i++){
			pComponents[i].setEnabled(!pLocked);
			
			if(pComponents[i] instanceof JPanel){
				Component[] childComponents = ((JPanel) pComponents[i]).getComponents();
				setLockedComponents(childComponents, pLocked);
			}
		}
	}
}